<?php


namespace App\Models\CacheModel\live;


use app\common\lib\Util;
use App\Models\Api\BaseCache;
use think\Cache;
use think\Db;
use think\Log;
use AstroTool\Cache\CacheManage;

class LiveRecordUserHot extends BaseCache
{
    /**
     * 用户热度表创建
     * @param $liveId
     * @return bool
     */
    public function createUserHotTable($liveId)
    {
        $tableName1 = 'live_user_hot_' . $liveId;

        $isTable = Db::query('select `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` where `TABLE_SCHEMA`="live_data" and `TABLE_NAME`="' . $tableName1 . '"');
        if (!$isTable)
        { // 表不存在则创建
            try
            {
                $str = "CREATE TABLE `live_data`.`{$tableName1}` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `uid` int(11) NOT NULL DEFAULT 0 COMMENT '用户ID',
                          `live_record_id` int(11) NOT NULL DEFAULT 0 COMMENT '直播记录ID',
                          `zan_hot` int(11) NOT NULL DEFAULT 0 COMMENT '点赞热度值',
                          `message_hot` int(11) NOT NULL DEFAULT 0 COMMENT '消息热度值',
                          `gift_hot` int(11) NOT NULL DEFAULT 0 COMMENT '礼物热度值',
                          `total_hot` int(11) NOT NULL DEFAULT 0 COMMENT '总热度值',
                          `date`    int(11)  NOT NULL DEFAULT 0 COMMENT '日期【20210926】',
                          `create_time`    bigint(15)  NOT NULL DEFAULT 0 COMMENT '',
                          PRIMARY KEY (`id`),
                          KEY `uid` (`uid`),
                          KEY `uid_live_record_id_date` (`uid`,`live_record_id`,`date`)
                        )  ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='直播热度信息'";
                // 创建数据库
                Db::execute($str);
            }
            catch (\Exception $e)
            {
                if (!strstr($e->getMessage(), 'already exists'))
                {
                    Log::write("直播间弹幕表创建失败：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
                    return false;
                }
            }
        }

        $tableName2 = 'live_user_' . $liveId;

        $isTable = Db::query('select `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` where `TABLE_SCHEMA`="live_data" and `TABLE_NAME`="' . $tableName2 . '"');
        if (!$isTable)
        { // 表不存在则创建
            try
            {
                $str = "CREATE TABLE `live_data`.`{$tableName2}` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `uid` int(11) NOT NULL DEFAULT 0 COMMENT '用户ID',
                          `live_record_id` int(11) NOT NULL DEFAULT 0 COMMENT '直播记录ID',
                          `duration`    int(11)  NOT NULL DEFAULT 0 COMMENT '',
                          `login_time`    bigint(15)  NOT NULL DEFAULT 0 COMMENT '进入直播间时间',
                          `login_out_time`    bigint(15)  NOT NULL DEFAULT 0 COMMENT '退出直播间时间',
                          PRIMARY KEY (`id`),
                          KEY `uid` (`uid`),
                          KEY `live_record_id` (`live_record_id`),
                          KEY `uid_live_record_id_login_time` (`uid`,`live_record_id`,`login_time`),
                          KEY `login_time` (`login_time`)
                        )  ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='直播用户信息'";
                // 创建数据库
                Db::execute($str);
            }
            catch (\Exception $e)
            {
                if (!strstr($e->getMessage(), 'already exists'))
                {
                    Log::write("直播间用户表创建失败：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * @param $uid
     * @param $liveId
     * @param $liveRecordId
     * @param string $type 热度类型 点赞热度=》'zan_hot' 弹幕热度=》'message_hot' 礼物热度=》'gift_hot'
     * @param $inc
     * @return bool
     * @throws \Exception
     */
    public function userHotInc($uid, $liveId, $liveRecordId, string $type, $inc): bool
    {
        if (!in_array($type, ['zan_hot', 'message_hot', 'gift_hot'], true))
        {
            return false;
        }

        $date = (int)(date('Ymd'));

        CacheManage::getInstance()->setCacheConfig('live.record_user_hot', "{$date}:{$uid}:{$liveRecordId}")
            ->hashDataInc($type, $inc, function () use ($uid, $liveId, $liveRecordId, $date, $type, $inc)
            {
                try
                {
                    $data = $this->table('live_user_hot_' . $liveId)->where(['uid' => $uid, 'live_record_id' => $liveRecordId, 'date' => $date])
                        ->field('id,zan_hot,message_hot,gift_hot')->find();

                    if ($data)
                    {
                        return $data[$type] + $inc;
                    } else
                    {
                        $inserData = [
                            'uid' => $uid,
                            'live_record_id' => $liveRecordId,
                            'zan_hot' => 0,
                            'message_hot' => 0,
                            'gift_hot' => 0,
                            'total_hot' => $inc,
                            'date' => $date,
                            'create_time' => time()
                        ];
                        $inserData[$type] = $inc;

                        $this->table('live_user_hot_' . $liveId)->insert($inserData);

                        return $inc;
                    }
                }
                catch (\Exception $e)
                {
                    return 0;
                }
            });

        $isUpdateToData = Cache::get('live_cache_update_to_date:record_user_hot:' . $liveId . ':' . $uid, 0);

        if (!$isUpdateToData)
        {
            // 发送队列-》更新缓存内数据到数据库中
            Util::queuePush('live_cache_update_to_database', [
                'type' => 'record_user_hot',
                'data' => [
                    'date' => $date,
                    'uid' => $uid,
                    'live_id' => $liveId,
                    'live_record_id' => $liveRecordId,
                ],
            ], 60);
            // 记录已添加同步缓存到数据库
            Cache::set('live_cache_update_to_date:record_user_hot:' . $liveId . ':' . $uid, 1, 86400);
        }

        return true;
    }
}
